package com.cloudwave.trailends.ui;

import java.io.UnsupportedEncodingException;
import java.util.HashMap;
import java.util.Map;

import android.content.Intent;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.Log;
import android.view.View;
import android.widget.EditText;
import android.widget.ImageButton;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.alibaba.fastjson.JSON;
import com.cloudwave.trailends.AppContext;
import com.cloudwave.trailends.Constants;
import com.cloudwave.trailends.R;
import com.cloudwave.trailends.compo.BaseActivity;
import com.cloudwave.trailends.domain.User;
import com.cloudwave.trailends.entity.ResultEntity;
import com.cloudwave.trailends.entity.SsoEntity;
import com.cloudwave.trailends.utils.RegexUtils;
import com.cloudwave.trailends.utils.StatisticsUtils;
import com.cloudwave.trailends.widget.dialog.ColaProgress;
import com.lidroid.xutils.DbUtils;
import com.lidroid.xutils.HttpUtils;
import com.lidroid.xutils.exception.HttpException;
import com.lidroid.xutils.http.RequestParams;
import com.lidroid.xutils.http.ResponseInfo;
import com.lidroid.xutils.http.callback.RequestCallBack;
import com.lidroid.xutils.http.client.HttpRequest;
import com.umeng.socialize.bean.SHARE_MEDIA;
import com.umeng.socialize.controller.UMServiceFactory;
import com.umeng.socialize.controller.UMSocialService;
import com.umeng.socialize.controller.listener.SocializeListeners.UMAuthListener;
import com.umeng.socialize.controller.listener.SocializeListeners.UMDataListener;
import com.umeng.socialize.exception.SocializeException;
import com.umeng.socialize.sso.SinaSsoHandler;
import com.umeng.socialize.sso.UMQQSsoHandler;
import com.umeng.socialize.sso.UMSsoHandler;
import com.umeng.socialize.weixin.controller.UMWXHandler;

/**
 * @description 用户登录
 * @author 龙雪
 * 
 */

public class SigninActivity extends BaseActivity {
	private static final String TAG = "SigninActivity";
	
	final UMSocialService mController = UMServiceFactory.getUMSocialService("com.umeng.login");
	
	private ImageButton btnBack;
//	private ImageButton btnOK;
	private TextView tvTitle;
	private EditText etUsername;
	private EditText etPasswrod;
	private TextView tvSignin;
	private TextView tvSignup;
	private TextView tvLostPw;
	
	private ImageView ivQQLogin;
	private ImageView ivWXLogin;
	private ImageView ivWeiboLogin;
	
//	private DialogFragment loadingDialog;  //###考虑放到BaseActivity
//	private ProgressDialog dialog = null;
	private ColaProgress cp = null;
	
	@Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.signin);
        
        iniView();
        
//        dialog = new ProgressDialog(this);
//		dialog.setProgressStyle(ProgressDialog.STYLE_SPINNER); // 设置进度条的形式为圆形转动的进度条
//		dialog.setCancelable(true); // 设置是否可以通过点击Back键取消  
//        dialog.setCanceledOnTouchOutside(false); // 设置在点击Dialog外是否取消Dialog进度条 
    }
	
	
	private void iniView() {
		btnBack = (ImageButton) findViewById(R.id.btnBack);
		tvTitle = (TextView) findViewById(R.id.tvTitle);
//		btnOK = (ImageButton) findViewById(R.id.btnOK);
		etUsername = (EditText) findViewById(R.id.etUsername);
		etPasswrod = (EditText) findViewById(R.id.etPasswrod);
		tvSignin = (TextView) findViewById(R.id.tvSignin);
		tvSignup = (TextView) findViewById(R.id.tvSignup);
		tvLostPw = (TextView) findViewById(R.id.tvLostPw);
		
		tvTitle.setText(R.string.signin_title);
		tvLostPw.setVisibility(View.INVISIBLE);
		
		ivQQLogin = (ImageView) findViewById(R.id.ivQQLogin);
		ivWXLogin = (ImageView) findViewById(R.id.ivWXLogin);
		ivWeiboLogin = (ImageView) findViewById(R.id.ivWeiboLogin);
		
		String tmpUserName = ((AppContext) getApplication()).getAsString(Constants.CACHE_USER_NAME);
		
		if ( !TextUtils.isEmpty(tmpUserName) ) {
			etUsername.setText(tmpUserName);
		}
		
		btnBack.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				SigninActivity.this.finish();
			}
		});
		tvSignin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				signin();
			}
		});
		tvSignup.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				Intent intent = new Intent(SigninActivity.this, SignupActivity.class);
				startActivity(intent);
				SigninActivity.this.finish();
			}
		});
		tvLostPw.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				
			}
		});
		
		ivQQLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doOauthVerify(SHARE_MEDIA.QQ);
			}
		});
		ivWXLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doOauthVerify(SHARE_MEDIA.WEIXIN);
			}
		});
		ivWeiboLogin.setOnClickListener(new View.OnClickListener() {
			@Override
			public void onClick(View v) {
				doOauthVerify(SHARE_MEDIA.SINA);
			}
		});
		
	}
	
	@Override
	protected void onActivityResult(int requestCode, int resultCode, Intent data) {
	    super.onActivityResult(requestCode, resultCode, data);
//	    dialog.show();
	    /**使用SSO授权必须添加如下代码 */  
	    UMSsoHandler ssoHandler = mController.getConfig().getSsoHandler(requestCode);
	    if(ssoHandler != null){
	       ssoHandler.authorizeCallBack(requestCode, resultCode, data);
	    }
	}
	
	private void doOauthVerify(SHARE_MEDIA platform) {
		cp = ColaProgress.show(SigninActivity.this, "", true, false, null);
		
		if ( platform == SHARE_MEDIA.QQ ) {
			UMQQSsoHandler qqSsoHandler = new UMQQSsoHandler(SigninActivity.this, "101106052",
	                "6af1d40137e6f39d3478065816e0fc59");
			qqSsoHandler.addToSocialSDK();
			
//			if ( OauthHelper.isAuthenticatedAndTokenNotExpired(this, SHARE_MEDIA.QQ) ) {
//				String openid = OauthHelper.getUsid(this, SHARE_MEDIA.QQ);
//				signinWithSso(Constants.URL_SSO_SINGIN, null, openid, "qq");
//				return ;
//			}
		} else if ( platform == SHARE_MEDIA.WEIXIN ) {
//			// 添加微信平台
			UMWXHandler wxHandler = new UMWXHandler(this, "wxcce306117d7f202d", "fcca02e846e2929e6b7a3007d8711779");
			wxHandler.addToSocialSDK();
			mController.getConfig().setSsoHandler(wxHandler);
			
//			if ( OauthHelper.isAuthenticatedAndTokenNotExpired(this,SHARE_MEDIA.WEIXIN) ) {
//				String openid = OauthHelper.getUsid(this, SHARE_MEDIA.WEIXIN);
//				signinWithSso(Constants.URL_SSO_SINGIN, null, openid, "weixin");
//				return ;
//			}
		} else if ( platform == SHARE_MEDIA.SINA ) {
			mController.getConfig().setSsoHandler(new SinaSsoHandler());
			
//			if ( OauthHelper.isAuthenticatedAndTokenNotExpired(this,SHARE_MEDIA.SINA) ) {
//				String openid = OauthHelper.getUsid(this, SHARE_MEDIA.SINA);
//				signinWithSso(Constants.URL_SSO_SINGIN, null, openid, "weibo");
//				return ;
//			}
		}
		
		mController.doOauthVerify(SigninActivity.this, platform, new UMAuthListener() {
            @Override
            public void onError(SocializeException e, SHARE_MEDIA platform) { }
            
            @Override
            public void onComplete(Bundle value, SHARE_MEDIA platform) {
                if ( value != null && !TextUtils.isEmpty(value.getString("uid"))
                		&& !TextUtils.isEmpty(value.getString("openid"))) {
                    Toast.makeText(SigninActivity.this, "授权成功^_^", Toast.LENGTH_SHORT).show();
                    Log.d("Bundle value：",value.toString());
                    Map<String, Object> verifyMap = new HashMap<String, Object>();
                    
                    verifyMap.put("uid", value.getString("uid"));
                    verifyMap.put("openid", value.getString("openid"));
                    verifyMap.put("access_token", value.getString("access_token"));
                    verifyMap.put("pay_token", value.getString("pay_token"));
                    verifyMap.put("pfkey", value.getString("pfkey"));
                    verifyMap.put("expires_in", value.getString("expires_in"));
                    
                    getPlatformInfo(platform, verifyMap);
                    
                } else {
                	cp.dismiss();
                    Toast.makeText(SigninActivity.this, "授权失败~_~", Toast.LENGTH_SHORT).show();
                }
            }
            @Override
            public void onCancel(SHARE_MEDIA platform) { }
            
            @Override
            public void onStart(SHARE_MEDIA platform) { }
		});
	}
	
	private void getPlatformInfo(final SHARE_MEDIA platform, final Map<String, Object> verifyMap) {
		 cp.show();
		 
		//获取相关授权信息
        mController.getPlatformInfo(SigninActivity.this, platform, new UMDataListener() {
		    @Override
		    public void onStart() {
		        Toast.makeText(SigninActivity.this, "获取平台数据开始...", Toast.LENGTH_SHORT).show();
		    }                                              
		    @Override
	        public void onComplete(int status, Map<String, Object> info) {
	            if( status == 200 && info != null ) {
	                Log.d("info",info.toString());
	                
	                info.putAll(verifyMap);
	                signWithSso(Constants.URL_SSO_SING, platform, info);
	                
	            } else {
	            	cp.dismiss();
	               Log.d("getPlatformInfo-->onComplete","发生错误："+status);
	           }
	        }
		});
	}
	
//	private void signinWithSso(String url, String uid, String openid, String platform) {
//		RequestParams params = new RequestParams();
////		params.addHeader("api-version", "1");
////		String channelId = ((AppContext) getApplication()).getAppMeta("UMENG_CHANNEL");
////		params.addQueryStringParameter("channelId", channelId);  //URL参数方式有利于从访问日志统计访问量
//		StatisticsUtils.newInstance(this).appendParams("1", params);
//		
//		params.addBodyParameter("openid", openid);  //##考虑加密
//		params.addBodyParameter("platform", platform);
//		
//		HttpUtils http = new HttpUtils();
//		http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
//			@Override
//			public void onSuccess(ResponseInfo<String> responseInfo) {
//				
//				if (responseInfo.statusCode != 200 && TextUtils.isEmpty(responseInfo.result)) {
//					cp.dismiss();
//					Toast.makeText(SigninActivity.this, "未获取到返回数据,请重试!", Toast.LENGTH_SHORT).show();
//				} else {
//					Log.i(TAG, "获取到返回数据:"+responseInfo.result);
//					ResultEntity rt = JSON.parseObject(responseInfo.result, ResultEntity.class);
//					if ( rt.isSuccess() && rt.hasData() ) {
//						try {
////							UserInfo userInfo = JSON.parseObject(rt.data.toString(), UserInfo.class);
////							User user = userInfo.getUser();
//							User user = JSON.parseObject(rt.data.toString(), User.class);
//							user.isSessionUser(true);
//							Long currentTime = System.currentTimeMillis();
//							user.setCacheTime(currentTime);
//							((AppContext) getApplication()).cacheLoginUser(user);
//							
////							userInfo.setUser(null);
////							((AppContext) getApplication()).cacheLoginUserInfo(userInfo);
//							
//							// 写入到数据库
//							DbUtils dbu = DbUtils.create(SigninActivity.this, Constants.DB_NAME);
//							dbu.saveOrUpdate(user);
//							
//							Toast.makeText(SigninActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
//							
//							statUserData(SigninActivity.this);
//							
//							goToPage();
//						} catch (Exception e) {
//							cp.dismiss();
//							Toast.makeText(SigninActivity.this, "保存数据异常,请重试!", Toast.LENGTH_SHORT).show();
//							Log.e(TAG, "异常信息:"+e.getMessage());
//						}
//					} else {
//						cp.dismiss();
//						Toast.makeText(SigninActivity.this, rt.getCodeMsg(), Toast.LENGTH_SHORT).show();
//						return ;
//					}
//				}
//			}
//			@Override
//			public void onFailure(HttpException error, String msg) {
//				cp.dismiss();
//				Toast.makeText(SigninActivity.this, "登录失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
//				Log.d(TAG, error.getMessage());
//			}
//		});
//	}
	
	private void signWithSso(String url, SHARE_MEDIA platform, Map<String, Object> info) {
		SsoEntity ssoEntity = new SsoEntity(platform.toString(), info);
		
		RequestParams params = new RequestParams();
//		params.addHeader("api-version", "1");
//		
//		String channelId = ((AppContext) getApplication()).getAppMeta("UMENG_CHANNEL");
//		params.addQueryStringParameter("channelId", channelId);  //URL参数方式有利于从访问日志统计访问量
		StatisticsUtils.newInstance(this).appendParams("1", params);
		
		params.addBodyParameter("data", JSON.toJSONString(ssoEntity));  //URL参数方式有利于从访问日志统计访问量
		
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.POST, url, params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				
				if (responseInfo.statusCode != 200 && TextUtils.isEmpty(responseInfo.result)) {
					cp.dismiss();
					Toast.makeText(SigninActivity.this, "未获取到返回数据,请重试!", Toast.LENGTH_SHORT).show();
				} else {
					Log.i(TAG, "获取到返回数据:"+responseInfo.result);
					ResultEntity rt = JSON.parseObject(responseInfo.result, ResultEntity.class);
					if ( rt.isSuccess() && rt.hasData() ) {
						try {
//							UserInfo userInfo = JSON.parseObject(rt.data.toString(), UserInfo.class);
//							User user = userInfo.getUser();
							User user = JSON.parseObject(rt.data.toString(), User.class);
							user.isSessionUser(true);
							user.setCacheTime(System.currentTimeMillis());
							((AppContext) getApplication()).cacheLoginUser(user);
							
//							userInfo.setUser(null);
//							((AppContext) getApplication()).cacheLoginUserInfo(userInfo);
							
							// 写入到数据库
							DbUtils dbu = DbUtils.create(SigninActivity.this, Constants.DB_NAME);
							dbu.saveOrUpdate(user);
							
							Toast.makeText(SigninActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
							
							statUserData(SigninActivity.this);
							
							goToPage();
						} catch (Exception e) {
							cp.dismiss();
							Toast.makeText(SigninActivity.this, "保存数据异常,请重试!", Toast.LENGTH_SHORT).show();
							Log.e(TAG, "异常信息:"+e.getMessage());
						}
					} else {
						cp.dismiss();
						Toast.makeText(SigninActivity.this, rt.getCodeMsg(), Toast.LENGTH_SHORT).show();
						return ;
					}
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				cp.dismiss();
				Toast.makeText(SigninActivity.this, "登录失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
				Log.d(TAG, error.getMessage());
			}
		});
	}
	
	private void signin() {
//		resetSigninBtn(1);
		cp = ColaProgress.show(SigninActivity.this, "", true, false, null);
		
		String username = this.etUsername.getText().toString();
		String password = this.etPasswrod.getText().toString();
		
		if (TextUtils.isEmpty(username)) {
			Toast.makeText(SigninActivity.this, "账号不能为空!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		int len = 0;
		try {
			len = username.getBytes("utf-8").length;
		} catch (UnsupportedEncodingException e1) {
			len = 0;
		}
		
		String str = RegexUtils.filterAll(username);
		if ( TextUtils.isEmpty(str) ) {
			Toast.makeText(SigninActivity.this, "存在非法字符，只允许中文、字母、数字!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		} else {
			int lenTmp = 0;
			try {
				lenTmp = str.getBytes("utf-8").length;
			} catch (UnsupportedEncodingException e1) {
				lenTmp = 0;
			}
			if ( len > lenTmp ) {
				Toast.makeText(SigninActivity.this, "存在非法字符，只允许中文、字母、数字!", Toast.LENGTH_SHORT).show();
//				resetSigninBtn(2);
				return ;
			}
		}
		
		if (TextUtils.isEmpty(password)) {
			Toast.makeText(SigninActivity.this, "密码不能为空!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		int lenpwd = password.length();
		String pwd = RegexUtils.filtUnNcu(password);
		
		if ( pwd.length() < lenpwd ) {
			Toast.makeText(SigninActivity.this, "存在非法字符，只允许应为数字下划线!", Toast.LENGTH_SHORT).show();
//			resetSigninBtn(2);
			return ;
		}
		
		cp.show();
		
		RequestParams params = new RequestParams();
//		String pwdmd5 = MD5Encrypt.encrypt(passwrod);
		StatisticsUtils.newInstance(this).appendParams("1", params);
		params.addBodyParameter("username", username);
		params.addBodyParameter("password", password);
		
		HttpUtils http = new HttpUtils();
		http.send(HttpRequest.HttpMethod.POST, Constants.URL_SINGIN, params, new RequestCallBack<String>() {
			@Override
			public void onSuccess(ResponseInfo<String> responseInfo) {
				
				if (responseInfo.statusCode != 200 && TextUtils.isEmpty(responseInfo.result)) {
					Toast.makeText(SigninActivity.this, "未获取到返回数据,请重试!", Toast.LENGTH_SHORT).show();
//					resetSigninBtn(2);
					cp.dismiss();
					Log.i(TAG, "未获取到返回数据!");
				} else {
					Log.i(TAG, "获取到返回数据:"+responseInfo.result);
					ResultEntity rt = JSON.parseObject(responseInfo.result, ResultEntity.class);
					if ( rt.isSuccess() && rt.hasData() ) {
						try {
//							UserInfo userInfo = JSON.parseObject(rt.data.toString(), UserInfo.class);
//							User user = userInfo.getUser();
							User user = JSON.parseObject(rt.data.toString(), User.class);
							user.isSessionUser(true);
							Long currentTime = System.currentTimeMillis();
							user.setCacheTime(currentTime);
							((AppContext) getApplication()).cacheLoginUser(user);
							
//							userInfo.setUser(null);
//							((AppContext) getApplication()).cacheLoginUserInfo(userInfo);
							
							// 写入到数据库
							DbUtils dbu = DbUtils.create(SigninActivity.this, Constants.DB_NAME);
							dbu.saveOrUpdate(user);
							
							saveCache(user.getUserName());
							
							Toast.makeText(SigninActivity.this, "登录成功!", Toast.LENGTH_SHORT).show();
							
							statUserData(SigninActivity.this);
							
							goToPage();
						} catch (Exception e) {
							Toast.makeText(SigninActivity.this, "保存数据异常,请重试!", Toast.LENGTH_SHORT).show();
//							resetSigninBtn(2);
							cp.dismiss();
							Log.e(TAG, "异常信息:"+e.getMessage());
						}
					} else {
//						resetSigninBtn(2);
						cp.dismiss();
						Toast.makeText(SigninActivity.this, rt.getCodeMsg(), Toast.LENGTH_SHORT).show();
						return ;
					}
				}
			}
			@Override
			public void onFailure(HttpException error, String msg) {
				Toast.makeText(SigninActivity.this, "登录失败,请检查您的网络!", Toast.LENGTH_SHORT).show();
//				resetSigninBtn(2);
				cp.dismiss();
				Log.e(TAG, error.getMessage());
			}
		});
	}
	
	private void saveCache(String userName) {
		if ( !TextUtils.isEmpty(userName) ) {
			((AppContext) getApplication()).put(Constants.CACHE_USER_NAME, userName);
		}
	}
	
	private void goToPage() {
		Intent parIntent = this.getIntent();
		int page = parIntent.getIntExtra("page", 1);
		
		switch (page) {
		case 1:
			Intent intent1 = new Intent(SigninActivity.this, UserActivity.class);
			startActivity(intent1);
			this.finish();
			break;
		case 2:
			Intent intent2 = new Intent(SigninActivity.this, HistoryActivity.class);
			startActivity(intent2);
			this.finish();
			break;
		default:
			break;
		}
	}
	
//	private void resetSigninBtn(int code) {
//		etUsername.clearFocus();
//		etPasswrod.clearFocus();
//		
//		if (code == 1) {
//			tvSignin.setOnClickListener(null);
//			tvSignin.setBackgroundResource(R.color.them_gray);
//		} else if (code == 2) {
//			tvSignup.setBackgroundResource(R.color.white);
//			tvSignin.setOnClickListener(new View.OnClickListener() {
//				@Override
//				public void onClick(View v) {
//					signin();
//				}
//			});
//			tvSignin.setBackgroundResource(R.color.white);
//		}
//	}
	
}